<template>
  <view class="money-wrapper main-top" v-if="!id || (id && selected.tagId)">
    <view class="main-top-bar"/>
    <view style="position: fixed;background-color: white;width: 100%">
      <image src="/static/icons/back.svg" class="back" @click="backPress()"/>
      <CategorySection slot="title" :type.sync="selected.category"/>
    </view>
    <view class="main">
      <TagsSection :tags="tags" :tagId.sync="selected.tagId" :type.sync="selected.category"/>
    </view>
    <view style="position: fixed;bottom: 0;width: 100%">
      <KeyboardSection :amount.sync="selected.amount"
                       :note.sync="selected.note"
                       :createdAt.sync="selected.createdAt"
                       @onSubmit="saveRecord"/>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import CategorySection from '@/components/common/CategorySection'
import TagsSection from '@/main/Home/childComps/Money/TagsSection'
import KeyboardSection from '@/main/Home/childComps/Money/KeyboardSection'
import { httpPOST } from '@/common/req'

export default {
  components: { CategorySection, TagsSection, KeyboardSection },
  data() {
    return {
      id: '',
      selected: {
        tagId: 0, // 标签
        note: '', // 备注
        createdAt: new Date().toISOString(), // 日期
        category: '-', // 收入/支出
        amount: 0 // 总和
      }
    }
  },
  computed: {
    ...mapState(['tagList']),
    tags() {
      return this.tagList
    }
  },
  methods: {
    getDetail() {
      httpPOST({ url: 'book/record/get', param: { id: parseInt(this.id) } }).then(([err, res]) => {
        if (!err && res && res.data) {
          const { amount, category, createdAt, note, t_id } = res.data
          this.selected = { amount, category, createdAt, note, tagId: t_id }
        }
      })
    },
    updateRecord() {
      const param = this.selected
      param.t_id = param.tagId
      param.id = this.id
      delete param.tagId
      httpPOST({ url: 'book/record/update', param }).then(([err, res]) => {
        if (!err && res && res.data) {
          this.backPress()
        }
      })
    },
    saveRecord() {
      if (this.id) {
        this.updateRecord()
        return
      }
      this.$store.commit('createRecord', this.selected)
    },
    backPress() {
      uni.navigateBack({ delta: 1 })
    }
  },
  onLoad(e) {
    this.id = e.id || ''
    if (this.id) {
      this.getDetail()
    }
  }
}

</script>

<style lang="scss" scoped>
  .back{
    height: 52rpx;
    width: 52rpx;
    position: absolute;
    bottom: 20rpx;
    left: 24rpx
  }
  .money-wrapper {
    background-color: #fff;
    display: flex;
    flex-direction: column;

    .main {
      background-color: #fafbf6;
      padding-top: 68rpx;
      padding-bottom: calc( 100vh / 3 + 40px );
      flex: 1;
      overflow: auto;

      &::-webkit-scrollbar {
        display: none;
      }
    }
  }
</style>
